package tc.alert.tckejisoc.config;


import com.maxmind.geoip2.DatabaseReader;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;

@Configuration
public class GeoIPConfig {

    @Bean
    public DatabaseReader databaseReader() throws IOException {
        // 安全加载方式：从classpath读取并创建临时文件
        try (InputStream is = new ClassPathResource("GeoLite2-City.mmdb").getInputStream()) {
            File tempDB = File.createTempFile("geoip", ".mmdb");
            tempDB.deleteOnExit();
            Files.copy(is, tempDB.toPath(), StandardCopyOption.REPLACE_EXISTING);

            return new DatabaseReader.Builder(tempDB)
                    .fileMode(com.maxmind.db.Reader.FileMode.MEMORY)
                    .build();
        }
    }
}